package com.ghovos.usermangerpgdemo.common.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ghovos.usermangerpgdemo.entity.UserEntity;

import java.util.Date;

/**
 * @author liulingfeng6
 */
public class TokenUtils {

    /**token到期时间10小时*/
    public static final long EXPIRE_TIME = 10 * 60 * 60 * 1000;
    /**密钥盐*/
    private static final String TOKEN_SECRET = "Lf1141776830";

    /**
     * 生成token
     *
     * @param user
     * @return
     */
    public static String sign(UserEntity user) {

        Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token = JWT.create()
                //发行人
                .withIssuer("auth0")
                //存放数据
                .withClaim("id", user.getId())
                .withClaim("username", user.getUsername())
                //过期时间
                .withExpiresAt(expireAt)
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
        return "Bearer " + token;
    }


    /**
     * token验证
     *
     * @param token token
     * @return 返回值
     */
    public static DecodedJWT verify(String token) {
        token = token.replaceFirst("Bearer ", token);
        //创建token验证器
        return JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
                .withIssuer("auth0")
                .build()
                .verify(token);
    }

}